/*
 * Copyright 2021-2022 Open Kunlun Technology <https://www.openkunlun.io>
 */

package io.openkunlun.scaladsl.client

import akka.actor.{ ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider }
import akka.grpc.GrpcClientSettings
import io.openkunlun.scaladsl.v1

/**
 * @author ericxin.
 */
private[scaladsl] object DaprGrpcClient extends ExtensionId[DaprGrpcClient] with ExtensionIdProvider {
  override def lookup: ExtensionId[DaprGrpcClient] = DaprGrpcClient
  override def createExtension(system: ExtendedActorSystem) = new DaprGrpcClient(system)
}
private[scaladsl] class DaprGrpcClient(system: ExtendedActorSystem) extends Extension {
  private val maxInboundMessageSize: Int = system.settings.config.getConfig("akka.grpc.client.\"dapr.grpc\"").getInt("max-inbound-message-size")
  private val maxInboundMetadataSize: Int = system.settings.config.getConfig("akka.grpc.client.\"dapr.grpc\"").getInt("max-inbound-metadata-size")
  private val clientSettings: GrpcClientSettings = GrpcClientSettings.fromConfig("dapr.grpc")(system)
    .withChannelBuilderOverrides(_.maxInboundMessageSize(maxInboundMessageSize))
    .withChannelBuilderOverrides(_.maxInboundMetadataSize(maxInboundMetadataSize))

  //  private val poolSize = system.settings.config.getInt("io.openkunlun.client.pool-size")
  //  private val pools: Seq[v1.DaprClient] = Seq.fill(poolSize)(io.openkunlun.scaladsl.v1.DaprClient(clientSettings.withTls(clientSettings.trustManager.nonEmpty))(system))
  //
  //  def client: v1.DaprClient = pools(ThreadLocalRandom.current().nextInt(poolSize))

  val client: v1.DaprClient = io.openkunlun.scaladsl.v1.DaprClient(clientSettings.withTls(clientSettings.trustManager.nonEmpty))(system)
}
